package com.kdzy.lshy.socity_server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.kdzy.lshy.socity_server.common.Constants;
import com.kdzy.lshy.socity_server.common.QiNiu;
import com.kdzy.lshy.socity_server.common.ResultMap;
import com.kdzy.lshy.socity_server.repository.BaseDao;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.util.*;

/**
 * @author rtt
 */
//用户登录service
@Service
public class UserService extends BaseService {
    ;
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Resource
    private BaseDao baseDao;

    //根据条件登录
    public Object userLogin(String param, HttpServletRequest request) {
        String status = null;
        String info = null;
        Object content = null;

        try {
            if (StringUtils.isNoneBlank(StringUtils.trim(param))) {

                JSONObject jsonObject = JSON.parseObject(param);
                String password = jsonObject.getString("password");
                String dweller_idcard = jsonObject.getString("dweller_idcard");
                String telphone = jsonObject.getString("telphone");
                Integer visitPlat = (Integer) jsonObject.get("visit_plat");//访问平台
                Integer visit_type = jsonObject.getInteger(" visit_type");//访问类型	0测试  1生产
                Integer version = jsonObject.getInteger("version ");////数据版本 0:测试 1:生产
                Integer is_used = jsonObject.getInteger("is_used");//数据是否使用：0有效 1失效
                Long stamp = (Long) jsonObject.getLong("stamp"); // 时间戳

                List<Map<String, Object>> list = null;
                List<Object> tags = new ArrayList<Object>();
                if (dweller_idcard != null && dweller_idcard != "" && password != null && password != "") {
                    String sql = "select * from dweller d where 1=1";
                    StringBuilder sql1 = new StringBuilder(sql);
                    if (StringUtils.isNoneBlank(StringUtils.trim(dweller_idcard))) {
                        sql1.append(" and d.dweller_idcard =?");
                        tags.add(dweller_idcard);
                    }
                    if (StringUtils.isNoneBlank(StringUtils.trim(password))) {
                        sql1.append(" and d.password =?");
                        tags.add(password);
                    }
                    if (visit_type != null) {
                        sql1.append(" and d.visit_type =?");
                        tags.add(visit_type);
                    }
                    if (version != null) {
                        sql1.append(" and d.version =?");
                        tags.add(version);
                    }
                    if (is_used != null) {
                        sql1.append(" and d.is_used =?");
                        tags.add(is_used);
                    }
                    list = baseDao.queryForList(sql1.toString(), tags.toArray());
                    logger.info(String.valueOf(list.size()));
                }
                if (telphone != null && telphone != "" && password != null && password != "") {
                    String sql = "select * from dweller d where 1=1";
                    StringBuilder sql1 = new StringBuilder(sql);
                    if (StringUtils.isNoneBlank(StringUtils.trim(telphone))) {
                        sql1.append(" and d.telphone =?");
                        tags.add(telphone);
                    }
                    if (StringUtils.isNoneBlank(StringUtils.trim(password))) {
                        sql1.append(" and d.password =?");
                        tags.add(password);
                    }
                    if (visit_type != null) {
                        sql1.append(" and d.visit_type =?");
                        tags.add(visit_type);
                    }
                    if (version != null) {
                        sql1.append(" and d.version =?");
                        tags.add(version);
                    }
                    if (is_used != null) {
                        sql1.append(" and d.is_used =?");
                        tags.add(is_used);
                    }
                    list = baseDao.queryForList(sql1.toString(), tags.toArray());
                    logger.info(String.valueOf(list.size()));
                }
                if (list.size() > 0) {
                    request.getSession().setAttribute("list", list);
                    status = Constants.http_status_success;
                    info = Constants.http_info_success;
                    content = list;//获取集合中的第一条数据
                }
                if (list.size() == 0) {
                    status = Constants.password_wrong;
                    info = "工号或密码错误，请重新输入";
                }
            } else {
                status = Constants.http_status_fk;
                info = Constants.http_info_bank;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = Constants.http_status_fail;
            info = Constants.http_info_error;
        }
        return ResultMap.creatReault(status, info, content);
    }

    //登出
    public Object edit(String param, HttpServletRequest request) {
        String status = null;
        String info = null;
        Object content = null;

        JSONObject jsonObject = JSON.parseObject(param);
        String dweller_idcard = jsonObject.getString("dweller_idcard");
        String sql = "select * from dweller where dweller.dweller_idcard='" + dweller_idcard + "'";
        List<Map<String, Object>> list = baseDao.queryForList(sql);
        try {
            if (list.size() > 0) {
                request.getSession().removeAttribute("list");
                status = Constants.http_status_success;
                info = Constants.http_info_success;
            }
            if (list.size() == 0) {
                status = Constants.http_status_fk;
                info = Constants.http_info_bank;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = Constants.http_status_fail;
            info = Constants.http_info_error;
        }
        return ResultMap.creatReault(status, info, content);
    }

    //身份证读取信息
    public void readIdCard(String filePath) {
        try {
            String encoding = "GBK";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String len = null;
                while ((len = bufferedReader.readLine()) != null) {
                    System.out.println(len);
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    //网页下载
    public Object packdownload(String param, HttpServletResponse response) {

        String status = null;
        String info = null;
        Object content = null;

        if (StringUtils.isNoneBlank(StringUtils.trim(param))) {

            JSONObject jsonObject = JSON.parseObject(param);
            String id = jsonObject.getString("id");
            Integer visitPlat = (Integer) jsonObject.get("visit_plat");//访问平台
            Integer visit_type = jsonObject.getInteger(" visit_type");//访问类型	0测试  1生产
            Integer version = jsonObject.getInteger("version ");////数据版本 0:测试 1:生产
            Integer is_used = jsonObject.getInteger("is_used");//数据是否使用：0有效 1失效
            Long stamp = (Long) jsonObject.getLong("stamp"); // 时间戳

            String sql = "select br.note from bizz b,bizz_resource br where br.bizz_id=b.ID";

            StringBuilder sql1 = new StringBuilder(sql);
            List<Object> tags = new ArrayList<Object>();

            if (StringUtils.isNoneBlank(StringUtils.trim(id))) {
                sql1.append(" and b.ID= ?");
                tags.add(id);
            }
            if (visit_type != null) {
                sql1.append(" AND br.visit_type = ?");
                tags.add(visit_type);
            }
            if (version != null) {
                sql1.append(" AND br.version = ?");
                tags.add(version);
            }
            if(is_used!=null){
                sql1.append(" AND br.is_used = ?");
                tags.add(is_used);
            }
            try {
                if(is_used==2) {
                    if(visitPlat==0){
                        List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
                        String note = (String) list.get(0).get("note");

                        OkHttpClient client = new OkHttpClient();
                        Request req = new Request.Builder().url(note).build();
                        okhttp3.Response resp = client.newCall(req).execute();
                        logger.info(String.valueOf(resp.isSuccessful()));

                        InputStream is=null;
                        if(resp.isSuccessful()){
                            ResponseBody body = resp.body();
                            is = body.byteStream();
                        }
                        response.setContentType("application/octet-stream");
                        response.setHeader("Content-disposition", "attachment;filename=" + new String("办事指南".getBytes("UTF-8"), "ISO8859-1") + ".zip");
                        OutputStream out = null;
                        out = response.getOutputStream();
                        int length = 0;
                        byte[] buf = new byte[1024];
                        while ((length = is.read(buf)) > 0) {
                            out.write(buf, 0, length);
                        }
                        out.flush();
                        out.close();
                        return null;
                    }else{
                        List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
                        if (list.size() > 0) {
                            String res_zip_url = (String) list.get(0).get("note");
                            status = Constants.http_status_success;
                            info = Constants.http_info_success;
                            content = res_zip_url;
                        }
                        if (list.size() == 0) {
                            status = Constants.http_status_fk;
                            info = Constants.http_info_bank;
                        }
                }
                }
            } catch (Exception e) {
                e.printStackTrace();
                status = Constants.http_status_fail;
                info = Constants.http_info_error;
            }
        }
        return ResultMap.creatReault(status, info, content);
    }

    //网页下载 - 本地
    public Object packdownload2(String param, HttpServletResponse response) {

        String status = null;
        String info = null;
        Object content = null;

        if (StringUtils.isNoneBlank(StringUtils.trim(param))) {

            JSONObject jsonObject = JSON.parseObject(param);
            String id = jsonObject.getString("id");
            Integer visitPlat = (Integer) jsonObject.get("visit_plat");//访问平台
            Integer visit_type = jsonObject.getInteger(" visit_type");//访问类型	0测试  1生产
            Integer version = jsonObject.getInteger("version ");////数据版本 0:测试 1:生产
            Integer is_used = jsonObject.getInteger("is_used");//数据是否使用：0有效 1失效
            Long stamp = (Long) jsonObject.getLong("stamp"); // 时间戳

            String sql = "select br.note from bizz b,bizz_resource br where br.bizz_id=b.ID";

            StringBuilder sql1 = new StringBuilder(sql);
            List<Object> tags = new ArrayList<Object>();

            if (StringUtils.isNoneBlank(StringUtils.trim(id))) {
                sql1.append(" and b.ID= ?");
                tags.add(id);
            }
            if (visit_type != null) {
                sql1.append(" AND br.visit_type = ?");
                tags.add(visit_type);
            }
            if (version != null) {
                sql1.append(" AND br.version = ?");
                tags.add(version);
            }
            if(is_used!=null){
                sql1.append(" AND br.is_used = ?");
                tags.add(is_used);
            }
            try {
                if(is_used==2) {
                    if(visitPlat==0){
                        List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
                        String note = (String) list.get(0).get("note");

                        OkHttpClient client = new OkHttpClient();
                        Request req = new Request.Builder().url(note).build();
                        okhttp3.Response resp = client.newCall(req).execute();
                        logger.info(String.valueOf(resp.isSuccessful()));

                        InputStream is=null;
                        if(resp.isSuccessful()){
                            ResponseBody body = resp.body();
                            is = body.byteStream();
                        }
                        response.setContentType("application/octet-stream");
                        response.setHeader("Content-disposition", "attachment;filename=" + new String("办事指南".getBytes("UTF-8"), "ISO8859-1") + ".zip");
                        OutputStream out = null;
                        out = response.getOutputStream();
                        int length = 0;
                        byte[] buf = new byte[1024];
                        while ((length = is.read(buf)) > 0) {
                            out.write(buf, 0, length);
                        }
                        out.flush();
                        out.close();
                        return null;
                    }else{
                        List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
                        if (list.size() > 0) {
                            String res_zip_url = (String) list.get(0).get("note");

                            // 保存到本地，根域名下载
                            String fileName = res_zip_url.substring("https://res.kdzydev.cn/".length(), res_zip_url.indexOf("?"));
                            String savePath = "/usr/share/nginx/html/public/" + fileName;

                            URL url = new URL(res_zip_url);/*将网络资源地址传给,即赋值给url*/
                            /*此为联系获得网络资源的固定格式用法，以便后面的in变量获得url截取网络资源的输入流*/
                            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                            DataInputStream in = new DataInputStream(connection.getInputStream());
                            /*此处也可用BufferedInputStream与BufferedOutputStream*/
                            DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
                            /*将参数savePath，即将截取的图片的存储在本地地址赋值给out输出流所指定的地址*/
                            byte[] buffer = new byte[4096];
                            int count = 0;
                            /*将输入流以字节的形式读取并写入buffer中*/
                            while ((count = in.read(buffer)) > 0) {
                                out.write(buffer, 0, count);
                            }
                            out.close();/*后面三行为关闭输入输出流以及网络资源的固定格式*/
                            in.close();
                            connection.disconnect();
                            //返回内容是保存后的完整的URL

                            status = Constants.http_status_success;
                            info = Constants.http_info_success;
                            content = "https://res.kdzydev.cn:8443/" + fileName;
                        }
                        if (list.size() == 0) {
                            status = Constants.http_status_fk;
                            info = Constants.http_info_bank;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                status = Constants.http_status_fail;
                info = Constants.http_info_error;
            }
        }
        return ResultMap.creatReault(status, info, content);
    }

    //网页下载 - 后台生成二维码
    public Object packdownload4(String param, HttpServletResponse response) {

        String status = null;
        String info = null;
        Object content = null;

        if (!StringUtils.isBlank(param)) {
            JSONObject jsonObject = JSON.parseObject(param);
            String id = jsonObject.getString("id");  // 业务id
            Integer visitPlat = jsonObject.getInteger("visit_plat"); //访问平台 0网页 1一体机 2小程序
            Integer visit_type = jsonObject.getInteger("visit_type"); //访问类型	0测试  1生产
            Integer version = jsonObject.getInteger("version"); //数据版本 0:测试 1:生产
            Integer is_used = jsonObject.getInteger("is_used"); //数据是否使用：0有效 1失效 2下载zip路径
            Long stamp = jsonObject.getLong("stamp");  // 时间戳

            if (null == visitPlat || 2 != visitPlat) {
                logger.info("参数visitPlat为空或不等于2");
                status = Constants.http_status_fail;
                info = Constants.http_info_bank;
                content = "访问平台类型参数不对";
                return ResultMap.creatReault(status, info, content);
            }
            if (null == is_used || 2 != is_used) {
                logger.info("参数is_used为空或不等于2");
                status = Constants.http_status_fail;
                info = Constants.http_info_bank;
                content = "访问平台类型参数不对";
                return ResultMap.creatReault(status, info, content);
            }

            String sql = "select br.note from bizz b,bizz_resource br where br.bizz_id=b.ID";

            StringBuilder sql1 = new StringBuilder(sql);
            List<Object> tags = new ArrayList<Object>();

            if (StringUtils.isNoneBlank(StringUtils.trim(id))) {
                sql1.append(" and b.ID= ?");
                tags.add(id);
            }
            if (visit_type != null) {
                sql1.append(" AND br.visit_type = ?");
                tags.add(visit_type);
            }
            if (version != null) {
                sql1.append(" AND br.version = ?");
                tags.add(version);
            }
            if(is_used!=null){
                sql1.append(" AND br.is_used = ?");
                tags.add(is_used);
            }
            try {
                List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
                if (list.size() > 0) {
                    String res_zip_url = (String) list.get(0).get("note"); // zip可下载路径
                    // 将下载链接路径生成二维码图片
                    int width=300;      //图片的宽度
                    int height=300;     //图片的高度
                    String format="png";    //图片的格式

                    /**
                     * 定义二维码的参数
                     */
                    HashMap hints=new HashMap();
                    hints.put(EncodeHintType.CHARACTER_SET,"utf-8");    //指定字符编码为“utf-8”
                    hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);  //指定二维码的纠错等级为中级
                    hints.put(EncodeHintType.MARGIN, 2);    //设置图片的边距

                    /**
                     * 生成二维码
                     */
                    String newName = "code.png";
                    BitMatrix bitMatrix=new MultiFormatWriter().encode(res_zip_url, BarcodeFormat.QR_CODE, width, height,hints);
                    Path file=new File(newName).toPath();
                    MatrixToImageWriter.writeToPath(bitMatrix, format, file);

                    // 调用七牛上传
                    String qiniuPath = null;
                    QiNiu qiNiu = new QiNiu("O1mwgsXsFvpJO7F_G9Lc1KAWi60JYUp8LyD6CyNm", "2yF2OzZthjAsyQuKpw5_KdDUU3Xp5lNpq_Dj0cOS", "kdzy", "https://res.kdzydev.cn");
                    QiNiu.Result upload = qiNiu.upload( new FileInputStream(new File(newName)), newName);
                    if (upload.isError()) {
                        qiniuPath = upload.getUrl();
                        logger.info("七牛上传成功后返回地址：" + qiniuPath);

                        new File(newName).delete();

                        status = Constants.http_status_success;
                        info = Constants.http_info_success;
                        content = qiniuPath;
                        return ResultMap.creatReault(status, info, content);
                    } else{
                        logger.info("上传失败");
                        status = Constants.http_status_fail;
                        info = Constants.http_info_error;
                        content = "上传图片失败";
                        return ResultMap.creatReault(status, info, content);
                    }

                }
                if (list.size() == 0) {
                    status = Constants.http_status_fk;
                    info = Constants.http_info_bank;
                }
            } catch (Exception e) {
                e.printStackTrace();
                status = Constants.http_status_fail;
                info = Constants.http_info_error;
            }
        }
        return ResultMap.creatReault(status, info, content);
    }

    //网页下载 - 发送下载链接短信
    public Object packdownload3(String param, HttpServletResponse response) {

        String status = null;
        String info = null;
        Object content = null;

        if (StringUtils.isBlank(param)) {
            JSONObject jsonObject = JSON.parseObject(param);
            String id = jsonObject.getString("id");  // 业务id
            Integer visitPlat = jsonObject.getInteger("visit_plat"); //访问平台 0网页 1一体机 2小程序
            Integer visit_type = jsonObject.getInteger("visit_type"); //访问类型	0测试  1生产
            Integer version = jsonObject.getInteger("version"); //数据版本 0:测试 1:生产
            Integer is_used = jsonObject.getInteger("is_used"); //数据是否使用：0有效 1失效 2下载zip路径
            Long stamp = jsonObject.getLong("stamp");  // 时间戳

            String dwellerId = jsonObject.getString("dwellerId"); // 居民id
            if (StringUtils.isBlank(dwellerId)) {
                logger.info("参数dwellerId为空");
                status = Constants.http_status_fail;
                info = Constants.http_info_bank;
                content = "居民id为空";
                return ResultMap.creatReault(status, info, content);
            }
            if (null == visitPlat || 2 != visitPlat) {
                logger.info("参数visitPlat为空或不等于2");
                status = Constants.http_status_fail;
                info = Constants.http_info_bank;
                content = "访问平台类型参数不对";
                return ResultMap.creatReault(status, info, content);
            }
            if (null == is_used || 2 != is_used) {
                logger.info("参数is_used为空或不等于2");
                status = Constants.http_status_fail;
                info = Constants.http_info_bank;
                content = "访问平台类型参数不对";
                return ResultMap.creatReault(status, info, content);
            }

            String sql = "select br.note from bizz b,bizz_resource br where br.bizz_id=b.ID";

            StringBuilder sql1 = new StringBuilder(sql);
            List<Object> tags = new ArrayList<Object>();

            if (StringUtils.isNoneBlank(StringUtils.trim(id))) {
                sql1.append(" and b.ID= ?");
                tags.add(id);
            }
            if (visit_type != null) {
                sql1.append(" AND br.visit_type = ?");
                tags.add(visit_type);
            }
            if (version != null) {
                sql1.append(" AND br.version = ?");
                tags.add(version);
            }
            if(is_used!=null){
                sql1.append(" AND br.is_used = ?");
                tags.add(is_used);
            }
            try {
                if(is_used==2) {
                    List<Map<String, Object>> list = baseDao.queryForList(sql1.toString(), tags.toArray());
                    if (list.size() > 0) {
                        String res_zip_url = (String) list.get(0).get("note"); // zip可下载路径
                        String fileName = res_zip_url.substring("https://res.kdzydev.cn/".length(), res_zip_url.indexOf("?")); // 文件名

                        // 根据居民id查询居民注册时的手机号码



                        status = Constants.http_status_success;
                        info = Constants.http_info_success;
                        content = "短信已发送";
                    }
                    if (list.size() == 0) {
                        status = Constants.http_status_fk;
                        info = Constants.http_info_bank;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                status = Constants.http_status_fail;
                info = Constants.http_info_error;
            }
        }
        return ResultMap.creatReault(status, info, content);
    }
}


